package com.yqz.common.util;

import com.yqz.common.Constant;
import com.yqz.sys.domain.CompUser;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public abstract class WebUtil {

    public static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getRequest();
    }

    public static HttpSession getSession(){
        return getRequest().getSession();
    }

    public static ServletContext getContext(){
        return ContextLoader.getCurrentWebApplicationContext().getServletContext();
    }

    /**
     * 将当前用户放入session
     * @param user
     */
    public static void saveCurrentCompUser(CompUser user){
        getSession().setAttribute(Constant.CURRENT_USER,user);
    }

    /**
     * 获取当前session中的用户
     * @return
     */
    public static CompUser getCurrentCompUser(){
        Object obj = getSession().getAttribute(Constant.CURRENT_USER);
        if(obj != null && obj instanceof CompUser){
            return (CompUser) obj;
        }
        return null;
    }

}
